import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:honeypotflutter/public/public_alert.dart';
import 'package:permission_handler/permission_handler.dart';

class HLLocation {
  /*
  * 开启定位
  * */
  static Future<Position> startLocation() async {
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled.');
    }

    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      // 如果用户尚未授予位置权限，则请求权限
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.deniedForever) {
        return Future.error('Location permissions are permanently denied, we cannot request permissions.');
      }
      if (permission == LocationPermission.denied) {
        HLAlert.showSureCancelAlert(
          title: "开启定位服务",
          message: "您未开启或已拒绝访问您的定位服务，请前往设置开启",
          cancelLabel: "取消",
          okLabel: "前往设置",
          sureAction: (bool isOk) {
            if (isOk) {
              openAppSettings();
              return;
            }
            Get.back();
          },
        );
        return Future.error('Location permissions are denied');
      }
    }
    try {
      Position p = await Geolocator.getCurrentPosition();
      return p;
    } catch (error) {
      return Future.error(error);
    }
  }
}
